//
//  FYHomeTableViewController.swift
//  Weibo
//
//  Created by 冯毅 on 16/8/8.
//  Copyright © 2016年 冯毅. All rights reserved.
//

import UIKit

private let HomeTableViewCellIdentifier = "HomeTableViewCellIdentifier"

class FYHomeTableViewController: FYVisitorTableViewControlle {

    private lazy var statusListViewModel: FYStatusListViewModel = FYStatusListViewModel()
    
    //  风火轮
    private lazy var pullUpView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = UIColor.blueColor()
        return view
    }()
    //  系统的下拉刷新控件
    private lazy var refreshCtr: UIRefreshControl = {
        let ctr = UIRefreshControl()
        
        ctr.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
        return ctr
        
    }()
    
    //  自定义下拉刷新控件
    private lazy var pullDownView: FYRefreshControl = {
        
        let ctr = FYRefreshControl()
        
        ctr.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
        return ctr
        
    }()
    
    //  tip动画label
    private lazy var tipLabel: UILabel = {
        let label = UILabel(fontSize: 12, textColor: UIColor.whiteColor())
        label.backgroundColor = UIColor.orangeColor()
        label.text = "没有加载到微博数据"
        label.textAlignment = .Center
        label.hidden = true
        return label
    }()
    
    private func setupUI() {
        //  设置tableView相关操作
        setupTableView()
        //  判断导航控制器是否存在,存在插入tiplabel
        if let nav = self.navigationController {
            tipLabel.frame = CGRect(x: 0, y: CGRectGetMaxY(nav.navigationBar.frame) - 30, width: nav.navigationBar.width, height: 30)
            
            nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if isLogin {
            
           //   设置tableView相关操作
            setupUI()
            loadData()
        } else {
            visitorView?.updateVisitorViewInfo(nil, imageName: nil)
        }
    
    }

    //  设置tableView相关操作
    private func setupTableView() {
        
        tableView.registerClass(FYStatusTableViewCell.self, forCellReuseIdentifier: HomeTableViewCellIdentifier)
        //  设置行高 
        //  自动计算行高
        tableView.rowHeight = UITableViewAutomaticDimension
        //  预估高度
        tableView.estimatedRowHeight = 200
        
        tableView.separatorStyle = .None
        
        tableView.tableFooterView = pullUpView
        
        pullUpView.sizeToFit()
        
//        tableView.addSubview(pullUpView)
//        
//        tableView.addSubview(refreshCtr)
        
        tableView.addSubview(pullDownView)
    }
    
    @objc private func pullDownRefresh() {
        loadData()
    }
    
    private func endRefreshing() {
        
        //  停止菊花转
        pullUpView.stopAnimating()
        //  结束系统下拉刷新的状态
        refreshCtr.endRefreshing()
        //  结束自定义下拉刷新的状态
        pullDownView.endRefreshing()
        
    }
    
    //  根据服务端返回的信息显示tip文字
    private func startAnimation(message: String) {
        
        //  判断视图如果显示表示正在执行动画,让其直接返回不执行下面代码
        if tipLabel.hidden == false {
            return
        }
        
        //  设置显示文字
        tipLabel.text = message
        
        //  显示tiplabel
        tipLabel.hidden = false
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.tipLabel.transform = CGAffineTransformMakeTranslation(0, self.tipLabel.height)
            }) { (_) -> Void in
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.tipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        //  隐藏tiplabel
                        self.tipLabel.hidden = true
                })
        }
        
        
        
    }
    
    private func loadData() {
        
        statusListViewModel.loadData(pullUpView.isAnimating()) { (isSuccess,message) -> () in
            //  开启tip动画
            if !self.pullUpView.isAnimating() {
                self.startAnimation(message)
            }
            
            
            
            self.endRefreshing()
            
            if isSuccess {
                //  数据请求成功重写刷新数据
                self.tableView.reloadData()
            } else {
                print("数据请求异常")
            }
            
        }
        
    }
    


   
}
extension FYHomeTableViewController {
    // MARK: - Table view data source
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of rows
        return statusListViewModel.statusList.count
    }
    
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeTableViewCellIdentifier, forIndexPath: indexPath) as! FYStatusTableViewCell
        
        cell.statusViewModel = statusListViewModel.statusList[indexPath.row]
        
        cell.selectionStyle = .None
        
        return cell
    }

    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == statusListViewModel.statusList.count - 1 && !pullUpView.isAnimating() {
            print("已经是最后一条微博数据了")
            //  开启风火轮
            pullUpView.startAnimating()
            //  加载更多数据
            loadData()
        }
        
    }
}